package cn.wm.server;

import cn.hutool.log.Log;
import cn.hutool.log.StaticLog;
import cn.wm.constant.MessageType;
import cn.wm.struct.Message;
import cn.wm.struct.MessageHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * HeartBeatRespHandler
 *
 * @author wm
 * @version 1.0
 * 2021/6/25 14:32
 **/
public class HeartBeatRespHandler extends SimpleChannelInboundHandler<Message> {

    private static final Log log = StaticLog.get();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message message) throws Exception {
        if (message.getHeader() != null && message.getHeader().getType() == MessageType.HEARTBEAT_REQ.value()) {
            log.info("Receive client heart beat message : ---> {} ", message);
            Message heartBeat = buildHeatBeat();
            log.info("Send heart beat response message to client : ---> {}", heartBeat);
            ctx.writeAndFlush(heartBeat);
        } else {
            ctx.fireChannelRead(message);
        }
    }

    private Message buildHeatBeat() {
        Message message = new Message();
        MessageHeader header = new MessageHeader();
        header.setType(MessageType.HEARTBEAT_RESP.value());
        message.setHeader(header);
        return message;
    }
}
